﻿using Bridge.Shared.Helper;
using Bridge.Shared.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bridge.Shared.Middlewares
{
    public class GlobalExceptionMiddleware
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();
        private readonly RequestDelegate next;
        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            if(ex != null)
            {
                logger.Error(ex);
                context.Response.ContentType = "text/plain;charset=utf-8";
                var response = ResponseResult.Fail(ex.Message);
                await context.Response.WriteAsync(response.ToJson());

            }
             await next.Invoke(context);

        }
    }
}
